#ifndef __BLOCK_QUEUE_HPP__
#define __BLOCK_QUEUE_HPP__

#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>
#include <unistd.h>
using namespace std;
template <typename T>
class BlockQueue
{
public:
    BlockQueue(int cap) : _cap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_product_cond, nullptr);
        pthread_cond_init(&_consum_cond, nullptr);
        _productor_wait_num = 0;
        _consumer_wait_num = 0;
    }
    void Enqueue(T &in) // 生产者接口
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull())
        {
        //    std::cout << "生产者 "  << _block_queue.size() << std::endl;
           _productor_wait_num++;
            // 生产线程要等待
            pthread_cond_wait(&_product_cond, &_mutex);
             _productor_wait_num--;
        }
       // std::cout << "生产者开始生成" << std::endl;
        _block_queue.push(in);
        if(_consumer_wait_num>0)pthread_cond_signal(&_consum_cond);
        pthread_mutex_unlock(&_mutex);
    }
    void Pop(T *out) // 消费者接口
    {
        sleep(2);
        pthread_mutex_lock(&_mutex);
        while (IsEmpty())
        {
            
            _consumer_wait_num++;
            if( _productor_wait_num>0)
         pthread_cond_wait(&_consum_cond, &_mutex);
            _consumer_wait_num--;
        }
         // std::cout << "消费者开始消费" << std::endl;
        *out = _block_queue.front();
        _block_queue.pop();
        pthread_cond_signal(&_product_cond);    
        pthread_mutex_unlock(&_mutex);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cond);
        pthread_cond_destroy(&_consum_cond);
    }

private:
    bool IsFull()
    {
        return _block_queue.size() == _cap;
    }
    bool IsEmpty()
    {
        return _block_queue.empty();
    }
    queue<T> _block_queue;        // 阻塞队列
    int _cap;                     // 总上限
    pthread_mutex_t _mutex;       // 保护_block_queue
    pthread_cond_t _product_cond; // 给生产者提供的条件变量
    pthread_cond_t _consum_cond;  // 给消费者提供的条件变量
    int _productor_wait_num;
    int _consumer_wait_num;
};

#endif